package com.mediaideas.videoengine.recorder;

import android.util.Log;

import com.coremedia.iso.boxes.Container;
import com.googlecode.mp4parser.FileDataSourceImpl;
import com.googlecode.mp4parser.authoring.Movie;
import com.googlecode.mp4parser.authoring.Track;
import com.googlecode.mp4parser.authoring.builder.DefaultMp4Builder;
import com.googlecode.mp4parser.authoring.tracks.AACTrackImpl;
import com.googlecode.mp4parser.authoring.tracks.AppendTrack;
import com.mediaideas.videoengine.utils.FileUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.Channels;
import java.nio.channels.WritableByteChannel;
import java.util.ArrayList;
import java.util.List;

/**
 * 录音断点续存辅助类,使用google接口实现mp4文件拼接
 * 目前未使用,后续版本可以加以优化处理
 */
public class Mp4ParserWrapper {
    public static final String TAG = "Mp4ParserWrapper";
    public static final int FILE_BUFFER_SIZE = 1024;

    /**
     * Appends mp4 audios/videos: {@code anotherFileName} to {@code mainFileName}.
     */
    public static boolean append(String mainFileName, String anotherFileName) {
        boolean rvalue = false;
        try {
            File targetFile = new File(mainFileName);  //data/data/com.hangzhou.xyj/cache/tmprecord.aac
            File anotherFile = new File(anotherFileName);  //storage/emulated/0/XiYouJi/sound/Record_1460629095920.aac
            if (targetFile.exists() && targetFile.length() > 0) {
                String tmpFileName = mainFileName + ".tmp.aac";
                if (anotherFile.length() > 0) {
                    append(mainFileName, anotherFileName, tmpFileName);
                    copyFile(tmpFileName, mainFileName);
                }
                rvalue = new File(tmpFileName).delete();
            } else if (targetFile.createNewFile()) {
                // 第一次拼接到主文件
                copyFile(anotherFileName, mainFileName);
                rvalue = anotherFile.delete();
            }
        } catch (IOException e) {
            Log.e(TAG, "Append two mp4 files exception", e);
        }
        return rvalue;
    }


    private static void copyFile(final String from, final String destination) throws IOException {
        FileInputStream in = new FileInputStream(from);
        FileOutputStream out = new FileOutputStream(destination);
        copy(in, out);
        in.close();
        out.close();
    }

    private static void copy(FileInputStream in, FileOutputStream out) throws IOException {
        byte[] buf = new byte[FILE_BUFFER_SIZE];
        int len;
        while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
    }

    public static void append(final String firstFile, final String secondFile, final String newFile) throws IOException {
//        final Movie movieB = MovieCreator.build(new FileDataSourceImpl(firstFile));
//        final Movie movieA = MovieCreator.build(new FileDataSourceImpl(secondFile));
        AACTrackImpl trackA = new AACTrackImpl(new FileDataSourceImpl(firstFile));
        AACTrackImpl trackB = new AACTrackImpl(new FileDataSourceImpl(secondFile));
        final Movie finalMovie = new Movie();
        finalMovie.addTrack(trackA);
        finalMovie.addTrack(trackB);
//        final List<Track> movieOneTracks = movieA.getTracks();
//        final List<Track> movieTwoTracks = movieB.getTracks();

//        for (int i = 0; i < movieOneTracks.size() || i < movieTwoTracks.size(); ++i) {
//            finalMovie.addTrack(new AppendTrack(movieTwoTracks.get(i), movieOneTracks.get(i)));
//        }

        final Container container = new DefaultMp4Builder().build(finalMovie);

        final FileOutputStream fos = new FileOutputStream(new File(newFile));
        final WritableByteChannel bb = Channels.newChannel(fos);
        container.writeContainer(bb);
        fos.close();
    }


    /**
     * 合成files文件到
     *
     * @param finalFile 最后合成的文件
     * @param files     需要合成的文件
     * @return
     * @author yaohuix
     * @date 2016/5/17 10:50
     */
    public static void append(final String finalFile, File[] files) throws IOException {
        final Movie finalMovie = new Movie();
        List<Track> tracks = new ArrayList<>();
        for (File file : files) {
            tracks.add(new AACTrackImpl(new FileDataSourceImpl(file)));
        }
        finalMovie.addTrack(new AppendTrack(tracks.toArray(new Track[tracks.size()])));
        if (FileUtils.isFileExists(finalFile)) {
            FileUtils.deleteFile(finalFile);
        }
        FileUtils.createFile(new File(finalFile));
        final Container container = new DefaultMp4Builder().build(finalMovie);
        final FileOutputStream fos = new FileOutputStream(new File(finalFile));
        final WritableByteChannel bb = Channels.newChannel(fos);
        container.writeContainer(bb);
        fos.close();
        //删除文件
        List<String> list = new ArrayList<>();
        for (File file : files) {
            list.add(file.getAbsolutePath());
        }
        FileUtils.deleteFiles(list);
    }
}
